package LC;

import java.util.Stack;

/**
 * https://leetcode.com/problems/binary-search-tree-iterator/description/
 * Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
 * Calling next() will return the next smallest number in the BST.
 * Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
 * Credits:
 * Special thanks to @ts for adding this problem and creating all test cases.
 */
public class LC_173_BinarySearchTreeIterator_BinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        BSTIterator bstIterator = new BSTIterator(root);
        int next = bstIterator.next();
        System.out.println(next);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class BSTIterator {
        static Stack<TreeNode> stack = new Stack<>();

        BSTIterator(TreeNode root) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
        }

        static boolean hasNext() {
            return !stack.isEmpty();
        }

        static int next() {
            TreeNode minCurrent = stack.pop();
            if (minCurrent.right != null) {
                TreeNode rightNode = minCurrent.right;
                while (rightNode != null) {
                    stack.push(rightNode);
                    rightNode = rightNode.left;
                }
            }
            return minCurrent.val;
        }
    }
}